// 首頁
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'
import store from './store' //注册store
import axios from 'axios'

Vue.use(Router);
// 页面路由
const routes = [{
    path: "/index",
    component: Index
}];
// 路由配置
const router = new Router({
    scrollBehavior: () => ({ y: 0 }),
    mode: 'history',
    base: '/vframe/wxact/',
    routes
})

let base_url = 'http://www.cchzyc.com/vframe/wxact/index';
// 路由守卫
router.beforeEach((to, from, next) => {
    let state = eval('(' + getQueryString('state') + ')');//获取shopId
    if(!store.state.isLogin){//需要鉴权
        let code = getQueryString('code')//获取微信提供code
        let appid = 'wx223f017544c95e0d';
        if (code != -1) {//已鉴权
            console.log('已鉴权');
            store.commit('onlogin', {
                isLogin:true
            })
            let url = 'http://www.cchzyc.com/vframe/wx/callBack.do';
            axios.post(url,{"code":code,"helperid":state.helperid}).then(res=>{
                if(res.data.flag=="0"){
                    // 存储自身openid
                    let ownid = res.data.helperid;
                    store.commit('onownid', {
                        ownid: ownid
                    })
                }
            })
            if (state != null) {
                login(state, to, next);
            }
        } else if (code == -1) {//未鉴权
            console.log('未鉴权');
            let str = '';
            if(to.query.id){
                str = base_url+'?id='+to.query.id;
            }
            //携带分享者openid
            if(to.query.helperid){
                str += '&helperid='+to.query.helperid;
            }
            let qr = JSON.stringify(to.query);
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&response_type=code&scope=snsapi_userinfo&state=` + qr + '&redirect_uri=' + str + '#wechat_redirect';
        }
    }else{//已鉴权
        next();
    }
})
// 登录
function login(state, to, fb) {//成功后拿到shopId和openId去鉴权,获取token
    router.replace({
        path: to.path,
        query: state
    }, fb)
}
// 获取url传参
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    // var r = url.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return -1;
}
function UrlSearch() {
    var name, value;
    var str = location.href; //取得整个地址栏
    var num = str.indexOf("?");
    var o = {};
    str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

    var arr = str.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            o[name] = value;
        }
    }
    return o;
}
export default router